package com.lingjtx.common.security.common;

import com.lingjtx.common.redis.stream.RedisStreamPublisher;
import com.lingjtx.common.security.annotation.Permissions;
import com.lingjtx.common.security.model.PermsEntity;
import com.lingjtx.common.security.model.PermsListModel;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用于批量获取每个服务的权限字符，批量更新导入到数据库中
 */
@Component
public class PermsBatchSaveCmd implements ApplicationContextAware, CommandLineRunner {

    private ApplicationContext applicationContext;

    private final RedisStreamPublisher publisher;

    public PermsBatchSaveCmd(RedisStreamPublisher publisher) {
        this.publisher = publisher;
    }

    @Override
    public void run(String... args) {
        //获取使用RestController注解标注的的所有controller类
        Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(RestController.class);
        //遍历每个controller层
        List<PermsEntity> list = new ArrayList<>();
        controllers.forEach((k, v) -> {
            Class<?> clazz = AopUtils.getTargetClass(v);
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(Permissions.class)) {
                    Permissions permissions = method.getDeclaredAnnotation(Permissions.class);
                    if (!"".equals(permissions.name())) {
                        PermsEntity resource = new PermsEntity();
                        resource.setPermsId(permissions.value());
                        resource.setPermsName(permissions.name());
                        list.add(resource);
                    }
                }
            }
        });
        if (!list.isEmpty()) {
            // 更新插入数据
            publisher.publish(new PermsListModel(list));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
